import util.mydecorator
import util.lib as lib
import util.util as utils
import util.number as lnumber

import pandas as pd
from daily import get_daily_df

gb_dict = {
    #"10d": None,
    "20d": None,
    "30d": None,
    "60d": None,
    "100d": None,
    "300d": None,
}

gb_keys = [
    #"10d",
    "20d", 
    "30d",
    "60d",
    "100d",
    "300d"
    ]

# 计算差距
def cal_duration(df,t1,t2):
    duration = len(df[t2.name:t1.name])
    d10max = lnumber.cal_pct(df[t1.name:].head(10)["close"].max() , t1.close)
    d10min = lnumber.cal_pct(df[t1.name:].head(10)["close"].min() , t1.close)

    return duration,d10max, d10min

def cal_gb(df, key):

    global gb_dict

    tmp = df[
        (df["close"] >= df[key]) & (df["close"].shift() < df[key].shift()) |
        (df["close"] < df[key]) & (df["close"].shift() >= df[key].shift())
        ].copy()
    if len(tmp) == 0:
        return

    tmp["type"] = key

    tmp["disPct"] = round(100 * (df["close"]/df[key] -1), 2)

    tmp["duration"] = 0
    tmp["d10max"] = 0.0
    tmp["d10min"] = 0.0

    for i in range(len(tmp)):
        if i > 0:
            duration, d10max, d10min = cal_duration(df, tmp.iloc[i], tmp.iloc[i-1])

            tmp.loc[tmp.iloc[i].name,"duration"] = duration * (1 if tmp.iloc[i]["disPct"] >= 0 else -1)
            tmp.loc[tmp.iloc[i].name,"d10max"] = d10max
            tmp.loc[tmp.iloc[i].name,"d10min"] = d10min
    
    if gb_dict[key] is None:
        gb_dict[key] = tmp
    else :
        #gb_dict[key] = gb_dict[key].append(tmp)
        gb_dict[key] = utils.merge(gb_dict[key], tmp, False)


def cal(df):
    for key in gb_keys:
        cal_gb(df, key)

@util.mydecorator.calTime
def job():

    global gb_dict

    writer = pd.ExcelWriter(lib.data_path + "daily_gb_sta.xlsx")

    shares = lib.lib_get_all_stock()

    for item in shares.iterrows():
        stock_name = item[1]['name']
        print(stock_name)
        df = get_daily_df(stock_name)[-500:].copy()
        df['stock'] = stock_name
        df['category'] = item[1]['category']
        cal(df)

    for v in gb_keys:
        gb_dict[v][['stock','category','close','pct','next_pct',
        'gt20d','gt30d','gt60d','gt100d','gt300d',
        'disPct','duration', 
        'd10max','d10min',
        'type'
                    ]].to_excel(writer, sheet_name=v)

    writer.close()


if __name__ == '__main__':
    job()